<?php

namespace app\common\service;

use app\common\model\Message;
use app\common\model\MessageUser;
use app\user\model\Feedback;
use app\http\exception\ApiException;
use randy\tools\units\ExtendQueryHelper;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;

class FeedbackService extends BaseService
{
    public function getFeedbackList(ExtendQueryHelper $extendQueryHelper, $data)
    {
        $query = Feedback::build()
                         ->withJoin('user')
                         ->where($extendQueryHelper->where)
                         ->order($extendQueryHelper->sort, $extendQueryHelper->order);
        $list = $extendQueryHelper->is_page ? $query->_paginate() : $query->select();
        return $list;
    }

    public function getFeedbackItem($feedback_id)
    {
        return Feedback::build()
                       ->with(['user'])
                       ->findOrFail($feedback_id);
    }

    public function delFeedbackItem($feedback_id)
    {
        $info = Feedback::find($feedback_id);
        $info->is_datele = 1;
        return $info->save();
    }

    public function setFeedbackItem($id, $data)
    {
        $info = Feedback::find($id);
        $info->save($data);
        return $info;
    }


    public function addFeedbackItem($data)
    {
        $model = new Feedback();
        $model->save($data);
        return $model;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     */
    public function setFeedbackType($feedback_id, $feedback_type) : bool
    {
        $feedback = Feedback::build()
                            ->findOrFail($feedback_id);
        $feedback->feedback_type = $feedback_type;
        return $feedback->save();
    }

    public function reply($feedback_id, $reply_content) : bool
    {
        $feedback = Feedback::build()
                            ->findOrFail($feedback_id);
        $feedback->reply_content = $reply_content;
        $feedback->status = 1;
        $msg = new Message();
        $msg->save([
            'type'       => 4,
            'member'     => 1,
            'title'      => '您的意见反馈平台已处理',
            'content'    => $reply_content,
            'extra_data' => json_encode($feedback),
        ]);
        $msg_user = new MessageUser();
        $msg_user->save([
            'user_id'    => $feedback->user_id,
            'message_id' => $msg->message_id,
        ]);
        return $feedback->save();
    }


}
